<?php

namespace app\enterprise\controller;

use app\enterprise\model\course\ExamLinkTopic;
use app\enterprise\model\course\Exam as ExamModel;
use app\enterprise\service\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\Request;

use app\enterprise\model\course\Topic as TopicModel;
use app\enterprise\model\TrainType as TrainTypeModel;
use app\enterprise\model\course\ExamLinkTopic as ExamLinkTopicModel;

class Topic extends Enterprise
{
    public function list(Request $request)
    {
        $limit = input('size', 10);
        $page = input('page', 1);

        $userIds = userIds($this->adminId);
        $where = [];

//        $where[] = ['creator_id', 'in', $userIds];

        $where[] = ['status', '=', 1];
        if ($title = $request->param('title', '')) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        if ($type = $request->param('type', '')) {
            $where[] = ['type', '=', $type];
        }
        $type_ids = input('type_ids', []);
        $create_type = input('create_type', '');

//        if (empty($create_type)) {
//            return app('json')->fail('请选择要查询的是平台资源还是我的资源');
//        }

//        if ($create_type == 1) {
//            $where[] = ['company_id', '=', 0];
//        } else {
//            $where[] = ['company_id', '=', $this->adminId];
//        }

        // 公共资源
        $resource_type = input('resource_type', '');
        if ( !empty($resource_type) ) {
            // 我的资源, 包含公共的, 平台的, 我的
            if ( $resource_type == 1 || $resource_type == 2 ) {
                $where[] = [ 'resource_type','=', $resource_type ];
            } else if ( $resource_type == 3 ) {
                // 只查我的
                $where[] = ['creator_id', '=', $userIds];
                $where[] = [ 'resource_type','=', $resource_type ];
                // 我的资源, 包含公共的, 平台的, 我的
//                $where[] = [ 'resource_type','in', '1,2,3' ];
            }
        }

        $data = TopicModel::where($where)
            ->when($ids = input('ids', []), function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids = input('exclude_ids', []), function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
//            ->where(function ($query) use ($create_type) {
//                if (empty($create_type)) {
//                    $query->where('company_id', $this->adminId)->whereOr('company_id', 0);
//                } else if ($create_type == 1) {
//                    $query->where('company_id', 0);
//                } else {
//                    $query->where('company_id', $this->adminId);
//                }
//            })
            ->where(function ($query) use ($type_ids) {
                if (!empty($type_ids)) {
                    foreach ($type_ids as $typeId) {
                        $query->whereOr('type_ids', 'like', '%,' . $typeId . ',%');
                    }
                }

            })
            ->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                $options = '';
                $options2 = [];
                if ($item['a']) {
                    $options .= 'A.' . $item['a'];
                    $options2[] = 'A.' . $item['a'];
                }
                if ($item['b']) {
                    $options .= ' B.' . $item['b'];
                    $options2[] = 'B.' . $item['b'];
                }
                if ($item['c']) {
                    $options .= ' C.' . $item['c'];
                    $options2[] = 'C.' . $item['c'];
                }
                if ($item['d']) {
                    $options .= ' D.' . $item['d'];
                    $options2[] = 'D.' . $item['d'];
                }
                if ($item['e']) {
                    $options .= ' E.' . $item['e'];
                    $options2[] = 'E.' . $item['e'];
                }
                if ($item['f']) {
                    $options .= ' F.' . $item['f'];
                    $options2[] = 'F.' . $item['f'];
                }
                $item['options'] = $options;
                $item['options2'] = $options2;
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids']);
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item['type_name'] = implode(',', $types);
                } else {
                    $item['type_name'] = '';
                }

                if (!$item['answer'] || !is_string($item['answer'])) {
                    $item['answer'] = '';
                }
                $array = json_decode($item['answer'], true);

                if (is_array($array)) {
                    $item['answer'] =  implode(',', $array);
                }

                return $item;
            });
//        $list = $data->items();
//        $del_total_num = 0;
//        // 如果是 我的资源, 需要筛选出来 自己的
//        if ( $resource_type == 3 ) {
//            foreach ($list as $key => &$value) {
//                if ( $value['resource_type'] == 3 && $value['creator_id'] != $this->adminId ) {
//                    unset($list[$key]);
//                    $del_total_num += 1;
//                }
//            }
//        }

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }


    public function info(Request $request)
    {
        $trainTypes = DataType::getTrainType();
        $id = input('id', '');
        if ($id) {
            $data = TopicModel::find($id);
            try {
                $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
                $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
            } catch (\Exception $e) {
                $data['type_ids'] = [];
            }
        } else {
            $data = null;
        }

        return app('json')->success([
            'trainTypes' => $trainTypes,
            'data' => $data,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'type_ids', 'type', 'title', 'a', 'b', 'c', 'd','e','f','hour',
            'answer', 'desc', 'company_id'
        ]);

        $create_type = input('create_type', '');
        if (empty($create_type)) {
            return app('json')->fail('请选择要保存的是平台资源还是我的资源');
        }

        if ($create_type == 2) {
            $data['company_id'] = $this->adminId;
        } else{
            $data['company_id'] = 0;
        }

        $id = input('id', '');
        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'type|题目类型' => 'require|in:1,2,3',
                'title|题目内容' => 'require|max:255',
                'a|选项A' => 'require|max:255',
                'b|选项B' => 'require|max:255',
                'c|选项C' => 'max:255',
                'd|选项D' => 'max:255',
                'e|选项E' => 'max:255',
                'f|选项F' => 'max:255',
                'answer|题目答案' => 'require|array',
                'desc|题目解析' => 'require|max:65535',
            ])->check($data);
            $data['type_ids'] = ',' . implode(',', $data['type_ids']) . ',';

            $type = $data['type'];

            $answer = $data['answer'];

            $answer = array_filter($answer);

            if (count($answer) > 6) {
                return app('json')->fail('最多只能有4个正确答案');
            }

            if ($type == 1 || $type == 3) {
                if (count($answer) > 1) {
                    return app('json')->fail('单选和判断题型答案只能有一个');
                }
            }
            foreach ($answer as $key => $value) {

                if (empty($data[strtolower($value)])) {
                    return app('json')->fail('请填写正确的答案选项:选项' . $value .'为空');
                }
                if (!empty($value)) {
                    $answer[$key] = strtoupper($value);
                }
            }


            sort($answer, SORT_STRING);



            $data['answer'] = json_encode($answer);
            if (!$id) {
                // 是否是公共资源
                $resource_type = input('resource_type', '');
                if ( !empty($resource_type) )  {
                    $data['resource_type'] = $resource_type;
                }
                $data['creator_id'] = $this->adminId;
                $res = TopicModel::create($data);
                $id = $res->id;
            } else {

                $topic = TopicModel::getOne($id);

                if (!$topic) {
                    return app('json')->fail('未找到要操作的数据');
                }
                if ($topic['company_id'] != $this->adminId) {
                    return app('json')->fail('您无权修改该数据');
                }
                $res = TopicModel::update($data, [
                    'id' => $id
                ]);
            }
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        return app('json')->success(['id' => $id]);
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $question = TopicModel::where('status', 1)
            ->where('id', $id)
            ->find();
        if (!$id || !$question) {
            return app('json')->fail('未找到要删除的数据');
        }
        if ($question['company_id'] != $this->adminId) {
            return app('json')->fail('您无权删除该数据');
        }

        // 判断是否有试卷使用
        if (ExamLinkTopicModel::where('topic_id', $id)->find()) {
            return app('json')->fail('该题目已被试卷使用，请先删除试卷再删除题目');
        }

        TopicModel::dataDelete($id);
        return app('json')->success();
    }

    public function uploadFile(Request $request)
    {
        $file = $request->file('file');
        $path = $file->getRealPath();
        $sht = IOFactory::load($path);
        $sheet = $sht->getSheet(0);
        $data = $sheet->toArray();
        $index = 0;
        $trainTypes = TrainTypeModel::where('status', 1)
            ->select();
        $trainTypes = array_column($trainTypes->toArray(), null, 'title');
        $insertData = [];
        $create_type = input('create_type', '');

        if (empty($create_type)) {
            return app('json')->fail('请选择要上传的是平台资源还是我的资源');
        }

        // 公共资源
        $resource_type = input('resource_type', '');

        $company_id = $create_type == 2 ? $this->adminId : 0;
        foreach ($data as $k => $v) {
            $loop = [
                'title' => '', 'type' => '', 'a' => '', 'b' => '', 'c' => '', 'd' => '', 'e' => '','f' => '',
                'answer' => [], 'desc' => '', 'type_ids' => [], 'company_id' => $company_id
            ];
            if ( !empty($resource_type) ) {
                $loop['resource_type'] = $resource_type;
            }
            $loop['creator_id'] = $this->adminId;
            if ($index < 1) {
                $index++;
                continue;
            }
            // 判断此行数据是否都为空
            if (!trim($v[0]) && !trim($v[1]) && !trim($v[2]) && !trim($v[3]) && !trim($v[4]) && !trim($v[5]) && !trim($v[6]) && !trim($v[7]) && !trim($v[8]) && !trim($v[9]) && !trim($v[10])) {
                continue;
            }
            $typeNames = explode(',', trim($v[0]));
            if (!$typeNames) {
                return app('json')->fail("第" . ($index + 1) . "行：请填写培训类型");
            }
            foreach ($typeNames as $name) {
                if (!isset($trainTypes[$name])) {
                    return app('json')->fail("第" . ($index + 1) . "行：培训类型\"" . $name . "\"不存在");
                } else {
                    $loop['type_ids'][] = $trainTypes[$name]['id'];
                }
            }
            if (!$v[1] || !in_array($v[1], ['单选题', '多选题', '判断题'])) {
                return app('json')->fail('第' . ($index + 1) . '行：题目类型请填写“单选体”、“多选题”、“判断题”中的一个');
            }
            $loop['type'] = ['' => 0, '单选题' => 1, '多选题' => 2, '判断题' => 3][$v[1]];
            if (!trim($v[2])) {
                return app('json')->fail('第' . ($index + 1) . '行：请填写题目内容');
            }
            $loop['title'] = trim($v[2]);
            $loop['a'] = trim($v[3]);
            $loop['b'] = trim($v[4]);
            $loop['c'] = trim($v[5]);
            $loop['d'] = trim($v[6]);
            $loop['e'] = trim($v[7]);
            $loop['f'] = trim($v[8]);
            if (empty($loop['a']) || empty($loop['b'])) {
                return app('json')->fail('第' . ($index + 1) . '行：请填写选项A和选项B');
            }
            if (!trim($v[9])) {
                return app('json')->fail('第' . ($index + 1) . '行：填写正确答案');
            }
            $answer = strtoupper(trim($v[9])); // 获取并去除首尾空格
            $answerArray = array_map('trim', explode(',', $answer)); // 按逗号分割成数组
            if ($loop['type'] == 1 || $loop['type'] == 3) {
                if (count($answerArray) > 1) {
                    return app('json')->fail('第' . ($index + 1) . '行：单选题和判断题只能有一个正确答案');
                }
            }
            $answerJson = json_encode($answerArray, JSON_UNESCAPED_UNICODE);
            $loop['answer'] = $answerJson;
            $loop['desc'] = trim($v[10]);
            $loop['type_ids'] = ','.implode(',', $loop['type_ids']).',';
            $loop['create_time'] = time();
            $insertData[] = $loop;
            $index++;
        }
        if (count($insertData) < 1) {
            return app('json')->fail('没有可导入的数据');
        }
        $resultList = (new TopicModel())->saveAll($insertData);

        $topicIds = array_column($resultList->toArray(), 'id');

        return app('json')->success([
            'topic_ids' => $topicIds,
        ]);
    }

    public function randomGenerateTopic()
    {
        $dan_num = input('dan_num', '');
        $duo_num = input('duo_num', '');
        $pan_num = input('pan_num', '');
        $exam_id = input('exam_id', '');
        $resource_type = input('resource_type', '');

        $where = [];
        $where[] = ['status', '=', 1];
        if ( $resource_type == 3 ) {
            $userIds = userIds($this->adminId);
//            $where[] = ['creator_id', 'in', $userIds];
            $where[] = [ 'resource_type','in', '1,2,3' ];
        } else if ( $resource_type == 2 ){
            $where[] = [ 'resource_type','=', $resource_type ];
        } else {
            $where[] = [ 'resource_type','in', '1,2' ];
        }
        $data = [];
        $topicData = [];
        $last = 0; // 排序
        $wareids = [];
        $count = 0;
        if ( !empty($dan_num) ) {
            $data['dan'] = TopicModel::where('type', 1)
                ->where($where)
                ->orderRaw('rand()')
                ->limit($dan_num)
                ->select()
                ->toArray();
            $data['dan_count'] = count($data['dan']);
            $count += $data['dan_count'];
            if ( $data['dan_count'] != $dan_num ) {
                return app('json')->fail('单选题题库数量不够, 请先去添加');
            }

            foreach ( $data['dan'] as $v ) {
                $topicData[] = [
                    'exam_id' => $exam_id,
                    'topic_id' => $v['id'],
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
            $wareids['dan_wareids'] = implode(',', array_column($data['dan'], 'id'));
        }

        if ( !empty($duo_num) ) {
            $data['duo'] = TopicModel::where('type', 2)
                ->where($where)
                ->orderRaw('rand()')
                ->limit($duo_num)
                ->select()
                ->toArray();
            $data['duo_count'] = count($data['duo']);
            $count += $data['duo_count'];
            if ( $data['duo_count']  != $duo_num ) {
                return app('json')->fail('多选题题库数量不够, 请先去添加');
            }

            foreach ( $data['duo'] as $v ) {
                $topicData[] = [
                    'exam_id' => $exam_id,
                    'topic_id' => $v['id'],
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
            $wareids['duo_wareids'] = implode(',', array_column($data['duo'], 'id'));
        }

        if ( !empty($pan_num) ) {
            $data['pan'] = TopicModel::where('type', 3)
                ->where($where)
                ->orderRaw('rand()')
                ->limit($pan_num)
                ->select()
                ->toArray();
            $data['pan_count'] = count($data['pan']);
            $count += $data['pan_count'];
            if ( $data['pan_count'] != $pan_num ) {
                return app('json')->fail('判断题题库数量不够, 请先去添加');
            }

            foreach ( $data['pan'] as $v ) {
                $topicData[] = [
                    'exam_id' => $exam_id,
                    'topic_id' => $v['id'],
                    'sort'=>$last+1
                ];
                $last = $last+1;
            }
            $wareids['pan_wareids'] = implode(',', array_column($data['pan'], 'id'));
        }
        $data['count'] = $count;

        if ( !empty($topicData) ) {

            ExamModel::update($wareids, ['id' => $exam_id]);
             (new ExamLinkTopicModel())->saveAll($topicData);
        }
//        dump($topicData);
//        die;
        return app('json')->success($data);
    }

}